# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(ropls)
library(pROC)
library(egg)
library(randomForest)
library(Boruta)
library(magrittr)
library(optparse)
library(caret)
library(PRROC)
library(tidyverse)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

parent <- paste0("./")
createWhenNoExist(parent)

fileName <- "Classification_Result.txt"

if (!file.exists(fileName)) {
  quit(status = 0)
}

data <- read_tsv(fileName)

uniqGroup <- unique(data$ClassNote)
group1Data <- data %>%
  filter(ClassNote == uniqGroup[1])
group2Data <- data %>%
  filter(ClassNote == uniqGroup[2])

prRs <- pr.curve(group2Data$Value, group1Data$Value, curve = T)
auc <- prRs$auc.integral
if (auc < 0.5) {
  prRs <- pr.curve(group1Data$Value, group2Data$Value, curve = T)
  auc <- prRs$auc.integral
}

prDf <- prRs$curve %>%
  as.data.frame() %>%
  set_colnames(c("Recall", "Precision", "Cutoff")) %>%
  select("Cutoff", everything())
write.csv(prDf, "PR_Curve_Data.csv", row.names = F)

colors <- hsv(h = seq(0, 1, length = 100) * 0.8, s = 1, v = 1)
yBreaks <- seq(0, 1, 0.2)

plotData <- prRs$curve %>%
  as.data.frame() %>%
  arrange(desc(V2), V1)

plotData

p <- ggplot(data = plotData, aes(x = V1, y = V2, color = V3)) +
  theme_bw(base_size = 8.8, base_family = "Times") +
  theme(plot.title = element_text(size = 14, hjust = 0.5, face = "bold"), panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), axis.title.x = element_text(size = 14), axis.title.y = element_text(size = 14),
        axis.text.x = element_text(size = 12), axis.text.y = element_text(size = 12),
        plot.margin = unit(c(1, 0.5, 1, 0.5), "cm"), panel.border = element_rect(size = 0.75),
        legend.text = element_text(size = 9),legend.title = element_text(size = 11)
  ) +
  geom_line() +
  xlab("FPR") +
  ylab("Sensitivity") +
  ggtitle(str_c("AUC=", format(auc, digits = 3))) +
  labs(colour = "Cutoff") +
  scale_x_continuous("Recall", breaks = yBreaks) +
  scale_y_continuous("Precision", breaks = seq(0, 1, 0.2), limit = c(0, 1)) +
  scale_colour_gradientn(colours = colors, breaks = yBreaks)

pdfFileName <- paste0("PR_Curve.pdf")
ggsave(limitsize = FALSE, pdfFileName, p, width = 6, height = 6)






